package com.rightsidetech.commom.push;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IIGtPush;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 代理商app个推工具类
 *

 应用名称：	超威云商-代理商
 App Id：	xkTO0hxaYf8Vti5YsKAEw3
 App Key：	ahEk1l4DBL69Qzq4yecAcA
 App Secret：	y7iHjAPm2N8aVsbGhI4uX5
 Android包名：	com.whf.CWCloudAgentApp
 iOS bundleID：	com.whf.CWCloudAgentApp
 Master Secret：
 【个推·消息推送】  	9Hg5hUEHHm8uYV7mzED0m5
 */
public class AgentPushUtil {
    private static final String APPID = "xkTO0hxaYf8Vti5YsKAEw3";
    private static final String APPKEY = "ahEk1l4DBL69Qzq4yecAcA";
    private static final String MASTERSECRET = "9Hg5hUEHHm8uYV7mzED0m5";
    private static final String API = "http://sdk.open.api.igexin.com/apiex.htm";    //OpenService接口地址

    /**
     * 返回值
     */
    public static final int PUSH_SUCCESS = 1;
    public static final int PUSH_FAIL = 0;
    /**
     * 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
     */
    @SuppressWarnings("unused")
    private static final int TRANSMISSION_TYPE_IMMEDIATELY = 1;
    private static final int TRANSMISSION_TYPE_WAIT = 2;

    private AgentPushUtil() {
    }

    /**
     * 推送给一个人
     *
     * @param device 设备信息
     * @param model  推送消息
     * @return
     */
    public static int pushToSingle(Device device, PushModel model) {
        if (!isDeviceAvailable(device)) {
            return PUSH_FAIL;
        }
        List<String> deviceId = new ArrayList<String>();
        deviceId.add(device.getDeviceId());
        if (device.getDeviceType() == Device.DEVICE_TYPE_ANDROID) {
            return pushToListForAndroid(deviceId, model);
        } else {
            return pushToListForIos(deviceId, model);
        }
    }

    /**
     * 推送给多人
     *
     * @param devices
     * @param model
     * @return
     * @throws Exception
     */
    public static int pushToList(List<Device> devices, PushModel model) throws Exception {
        List<String> deviceIdsOfAndroid = new ArrayList<String>();
        List<String> deviceIdsOfIos = new ArrayList<String>();
        for (Device device : devices) {
            if (device.getDeviceType() == Device.DEVICE_TYPE_ANDROID) {
                deviceIdsOfAndroid.add(device.getDeviceId());
            } else if (device.getDeviceType() == Device.DEVICE_TYPE_IOS) {
                deviceIdsOfIos.add(device.getDeviceId());
            }
        }
        int resultAndroid = pushToListForAndroid(deviceIdsOfAndroid, model);
        int resultIos = pushToListForIos(deviceIdsOfIos, model);
        if (resultAndroid == PUSH_SUCCESS && resultIos == PUSH_SUCCESS) {
            return PUSH_SUCCESS;
        } else {
            return PUSH_FAIL;
        }
    }

    /**
     * 推送给安卓用户
     *
     * @param deviceIds
     * @param model
     * @return
     */
    private static int pushToListForAndroid(List<String> deviceIds,
                                            PushModel model) {
        // 显示每个用户的用户状态，false:不显示，true：显示
        System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
        // 推送主类
        IIGtPush push = new IGtPush(API, APPKEY, MASTERSECRET);
        try {
            push.connect();
            TransmissionTemplate template = new TransmissionTemplate();
            ListMessage message = new ListMessage();
            // 通知模版
            template.setAppId(APPID); // 应用APPID
            template.setAppkey(APPKEY); // 应用APPKEY
            template.setTransmissionType(TRANSMISSION_TYPE_WAIT);// 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
            /**
             *
             */
            template.setTransmissionContent(JSONObject.toJSONString(model)); // 透传内容（点击通知后SDK将透传内容传给你的客户端，需要客户端做相应开发）
            message.setData(template);
            message.setOffline(true);
            message.setOfflineExpireTime(24 * 3600 * 1000);
            // 接收者
            List<Target> targets = new ArrayList<Target>();
            Target target = null;
            for (String deviceId : deviceIds) {
                target = new Target();
                target.setAppId(APPID);
                target.setClientId(deviceId);
                targets.add(target);
            }
            // 推送前通过该接口申请“ContentID”
            String contentId = push.getContentId(message);
            IPushResult ret = push.pushMessageToList(contentId, targets);
            System.out.println(ret.getResponse().toString());
            return PUSH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PUSH_FAIL;
        }
    }

    /**
     * 推送给IOS用户
     *
     * @param deviceIds
     * @param model
     * @return
     */
    private static int pushToListForIos(List<String> deviceIds, PushModel model) {
        //显示每个用户的用户状态，false:不显示，true：显示
        System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
        // 推送主类
        IIGtPush push = new IGtPush(API, APPKEY, MASTERSECRET);
        try {
            push.connect();
            ListMessage message = new ListMessage();
            TransmissionTemplate template = new TransmissionTemplate();
            template.setAppId(APPID);                            //应用APPID
            template.setAppkey(APPKEY);                            //应用APPKEY
            template.setTransmissionType(TRANSMISSION_TYPE_WAIT);// 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动

            template.setTransmissionContent(JSON.toJSONString(model));    // 透传内容（点击通知后SDK将透传内容传给你的客户端，需要客户端做相应开发）
            APNPayload payload = new APNPayload();
            payload.setAutoBadge("+1");
            payload.setContentAvailable(1);
            payload.setSound("default");
            payload.setCategory("$由客户端定义");
            payload.setAlertMsg(getDictionaryAlertMsg(model.getTitle(), model.getText()));
            template.setAPNInfo(payload);
            message.setData(template);
            message.setOffline(true);
            message.setOfflineExpireTime(24 * 3600 * 1000);
            // 接收者
            List<Target> targets = new ArrayList<Target>();
            Target target = null;
            for (String deviceId : deviceIds) {
                target = new Target();
                target.setAppId(APPID);
                target.setClientId(deviceId);
                targets.add(target);
            }
            //推送前通过该接口申请“ContentID”
            String contentId = push.getContentId(message);
            IPushResult ret = push.pushMessageToList(contentId, targets);
            System.out.println(ret.getResponse().toString());
            return PUSH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return PUSH_FAIL;
        }
    }

    private static boolean isDeviceAvailable(Device userOnline) {
        if (userOnline == null) {
            return false;
        }
        if (userOnline.getDeviceId() == null || userOnline.getDeviceId().equals("")) {
            return false;
        }
        if (userOnline.getDeviceType() == 0 || userOnline.getRiderId() == null || userOnline.getRiderId().equals("")) {
            return false;
        }
        return true;
    }


    private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title, String body) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(body);
        alertMsg.setActionLocKey("ActionLockey");
        alertMsg.setLocKey("LocKey");
        alertMsg.addLocArg("loc-args");
        alertMsg.setLaunchImage("launch-image"); // iOS8.2以上版本支持
        alertMsg.setTitle(title);
        alertMsg.setTitleLocKey("TitleLocKey");
        alertMsg.addTitleLocArg("TitleLocArg");
        return alertMsg;
    }


    public static void main(String[] args) {
        Device userOnline = new Device();
//        userOnline.setDeviceId("7e62bf3eadfc983837b7fdc0040caec2");
        userOnline.setDeviceId("1db5f2d167e5447401e519bc6eeb650a");

        userOnline.setDeviceType(Device.DEVICE_TYPE_IOS);
        userOnline.setRiderId("1");
        PushModel model = new PushModel();
        model.setText("新订单");
        model.setTitle("骑程无忧666");
        model.setUnReadNum(1);
        model.setPushType(7);
        model.setStringId("1027");
        pushToSingle(userOnline, model);

    }
}
